﻿using learn_jquery_file_upload.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace learn_jquery_file_upload.Controllers
{
    public class FullController : Controller
    {
        private readonly IWebHostEnvironment webHostEnvironment;

        public FullController(IWebHostEnvironment webHostEnvironment)
        {
            this.webHostEnvironment = webHostEnvironment;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> Upload(IFormFile files)
        {
            var resultList = new List<UploadFilesResult>();
            var path = Path.Combine(webHostEnvironment.WebRootPath, "uploads/" + files.FileName);
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await files.CopyToAsync(stream);
            }

            UploadFilesResult uploadFiles = new UploadFilesResult();
            uploadFiles.Name = files.FileName + " HaHa";
            uploadFiles.Size = files.Length;
            uploadFiles.Type = "image/jpeg";
            uploadFiles.Url = "/uploads/" + files.FileName;
            uploadFiles.DeleteUrl = "/Full/Delete?file=" + files.FileName;
            uploadFiles.ThumbnailUrl = "/uploads/" + files.FileName;
            uploadFiles.DeleteType = "GET";

            resultList.Add(uploadFiles);
            return Json(new { files = resultList });
        }

        public JsonResult Delete(string file)
        {
            System.IO.File.Delete(Path.Combine(webHostEnvironment.WebRootPath, "uploads/" + file));
            return Json("OK");
        }
        public IActionResult Privacy()
        {
            return View();
        }
    }
}
